package com.cotx.userconsumer01.service.impl;

import com.cotx.userinterface.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    //远程服务调用客户端
    @Autowired
    private RestTemplate restTemplate;
    //支持负载均衡的调用客户端
   @Autowired
   private LoadBalancerClient loadBalancerClient;


   /**
    * 通过客户端负载均衡获取生产者的地址
    *
    */
   public String getServerUrl(){
       //通过客户端调用服务均衡器查找服务
       ServiceInstance serviceInstance = loadBalancerClient.choose("USERPROVIDER");
       //获取服务提供者服务器ip、端口号
       int port = serviceInstance.getPort();
       String ip = serviceInstance.getHost();
       //拼接调用地址
       String url="http://"+ip+":"+port;

       System.out.println(url);

       return url;

//       return "http://USERPROVIDER";
   }


    @Override
    public Map<String, Object> findAll() {
        String url=getServerUrl();
        Map<String,Object> map = restTemplate.getForObject(url + "/user/", Map.class);
        return map;
    }
}
